package com.neuedu.projectedu.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.projectedu.entity.User;
import com.neuedu.projectedu.mapper.UserMapper;
import com.neuedu.projectedu.service.UserService;
import com.neuedu.projectedu.utils.DateUtils;
import com.neuedu.projectedu.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@CacheConfig(cacheNames = {"userService"})
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    @Cacheable(value = "userService")
    public List<User> getUsers() {
        QueryWrapper queryWrapper = new QueryWrapper();
        List<User> list = userMapper.selectList(queryWrapper);
        System.out.println("redis中没有该数据");
        // 1. List => key id=> value对象转字符串
        // 2. Hash => key id=> value username:  password:
//        for (User user : list) {
//            redisUtils.hset(user.getId().toString(),"username",user.getUsername());
//        }
        // 3. Set
        // String
//        if()
//        redisUtils.set("user", JSON.toJSONString(list));
        return list;
    }

    @Override
    @CachePut(value = "user", key = "#user.id")
    public User update(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user.getUsername());
        if (this.count(queryWrapper) > 0) {
            return null;
        } else {
            this.updateById(user);
        }
        return this.getById(user.getId());
    }

    @Override
    public boolean register(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user.getUsername());
        if (this.count(queryWrapper) > 0) {
            return false;
        } else {
            return this.save(user);
        }
    }

    @Cacheable(value = "userService", key = "#username")
    @Override
    public int login(String username, String password) {
        // 0 该用户不存在
        // 1 用户存在，密码错误达3
        // 2 时间没达1小时
        // 3 成功
        // 4 密码错误
        // 判断错误次数
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        User user = this.getOne(queryWrapper);
        if (user != null) {
            //
            if (user.getErrorCount() != null && user.getErrorCount() >= 3) {
                if (DateUtils.diffDateTimeToHours(LocalDateTime.now(), user.getLastLoginTime()) >= 1) {
                    return login(queryWrapper, user, password);
                } else {
                    return 1;
                }
            } else {
                return login(queryWrapper, user, password);
            }
        } else {
            return 0;
        }
    }

    private int login(QueryWrapper queryWrapper, User user, String password) {
        // 允许登录
        queryWrapper.eq("password", password);
        if (this.count(queryWrapper) > 0) {
            return 3;
        } else {
            // 必须更新次数
            if (user.getErrorCount() == null) {
                user.setErrorCount(0);
            }
            user.setErrorCount(user.getErrorCount() + 1);
            user.setLastLoginTime(LocalDateTime.now());
            this.updateById(user);
            return 4;
        }
    }

    @Override
    @Cacheable(value = "user", key = "#id", condition = "#id>0", unless = "#id<6")
    public User getUser(Long id) {
        log.info("缓存数据");
        return this.getById(id);
    }

    @Override
    @CacheEvict(value = "user", key = "#id")
    public boolean remove(Long id) {
        log.info("删除缓存");
        return this.removeById(id);
    }


}
